package cc.ufinity.networkdiagnose.manager;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.StringTokenizer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import java.net.URL;
import java.net.URLEncoder;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.CookieStore;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import android.util.Log;

import cc.ufinity.networkdiagnose.util.HttpUtils;
@Deprecated
public class WebLoginHelper {

    private String m_Host = "";
    private String m_LogoutData = "";
    //private static CookieStore m_Cookies = new BasicCookieStore();

    public static String httpGet(String url) throws Exception {
        HttpClient client = null;
        String reply = null;
        try {
            client = getHttpClient();
            // ((AbstractHttpClient) client).setCookieStore(m_Cookies);
            HttpGet get = new HttpGet(url);
            HttpResponse response = client.execute(get);

            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                reply = EntityUtils.toString(response.getEntity());
            }
        } finally {
            if (null != client) {
                client.getConnectionManager().shutdown();
            }
        }

        return reply;
    }

    public static String httpPost(String url, List<NameValuePair> params) throws Exception {
        String reply = null;
        HttpClient client = null;

        try {
            client = getHttpClient();
            // ((AbstractHttpClient) client).setCookieStore(m_Cookies);
            HttpPost post = new HttpPost(url);
            post.setEntity(new UrlEncodedFormEntity(params));
            HttpResponse response = client.execute(post);
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                reply = EntityUtils.toString(response.getEntity());
            }

        } finally {
            if (null != client) {
                client.getConnectionManager().shutdown();
            }
        }

        return reply;
    }

    public static synchronized HttpClient getHttpClient() {
        /*
         * HttpParams params = new BasicHttpParams();
         * 
         * // 设置一些基本参数 HttpProtocolParams.setVersion(params,
         * HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset(params,
         * CHARSET); HttpProtocolParams.setUseExpectContinue(params, true);
         * HttpProtocolParams.setUserAgent(params,
         * "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)");
         * 
         * 
         * // 从连接池中取连接的超时时间 ConnManagerParams.setTimeout(params,
         * MANAGER_TIMEOUT); // 连接超时
         * HttpConnectionParams.setConnectionTimeout(params, REQUEST_TIMEOUT);
         * // 请求超时 HttpConnectionParams.setSoTimeout(params, SO_TIMEOUT);
         * 
         * // 设置我们的HttpClient支持HTTP和HTTPS两种模式 SchemeRegistry schReg = new
         * SchemeRegistry(); schReg.register(new Scheme("http",
         * PlainSocketFactory.getSocketFactory(), 80)); schReg.register(new
         * Scheme("https", SSLSocketFactory.getSocketFactory(), 443));
         * 
         * // 使用线程安全的连接管理来创建HttpClient ClientConnectionManager conMgr = new
         * ThreadSafeClientConnManager(params, schReg); return new
         * DefaultHttpClient(conMgr, params);
         */
        return HttpUtils.getSSLHttpClient();
    }

    public static String GetHttpResult(String url, String params) throws Exception {
        String result = "";
        if (params != null && params != "") {
            List<String> list = split(params, "&");
            List<NameValuePair> paramsList = listToPair(list);
            result = httpPost(url, paramsList);
        } else {
            result = httpGet(url);
        }
        return result;
    }

    public static List<String> split(String str, String delim) {
        List<String> splitList = null;
        StringTokenizer st = null;

        if (str == null)
            return splitList;
        if (str.indexOf("?") == 0) {
            str.substring(1);
        }
        if (delim != null)
            st = new StringTokenizer(str, delim);
        else
            st = new StringTokenizer(str);

        if (st != null && st.hasMoreTokens()) {
            splitList = new ArrayList<String>();
            while (st.hasMoreTokens())
                splitList.add(st.nextToken());
        }
        return splitList;
    }

    public static List<NameValuePair> listToPair(List<String> list) {
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        if (list == null) {
            return null;
        }
        Iterator<String> iter = list.iterator();
        while (iter.hasNext()) {
            String iterStr = (String) iter.next();
            int num = iterStr.indexOf("=");
            params.add(new BasicNameValuePair(iterStr.substring(0, num), iterStr.substring(num + 1)));
        }
        return params;
    }

    public boolean CMCCLogin(String uName, String uPassword) {
        String tag = "CMCCLogin";
        try {
            // step 1 http://www.baidu.com/
            String url = "http://www.baidu.com/";
            String linfo = "";
            String result = GetHttpResult(url, null);
            Log.d(tag, "step1:"+result);

            // step 2 http://221.176.1.140:8080/wlan/index.php
            String post = "";
            String[] empties = result.split("\"");
            for (int i = 0; i < empties.length; i++) {
                if (empties[i].contains("action=")) {
                    url = empties[i + 1];
                }

                if (empties[i].trim().equals("hidden"))
                    post += post == "" ? (empties[i + 2] + "=" + empties[i + 4]) : ("&" + empties[i + 2] + "=" + empties[i + 4]);
            }
            linfo = post.substring(0, post.lastIndexOf('&'));

            // step 3
            // https://221.176.1.140:8090/input.php?wlanacip=211.138.149.13&wlanacname=9003.0591.591.00&wlanuserip=183.250.17.62&wlanacssid=&fromlocation=index
            result = GetHttpResult(url, post);
            Log.d(tag, "step3:"+result);
            empties = result.split("\'");
            for (int i = 0; i < empties.length; i++) {
                if (empties[i].contains("frame src=")) {
                    url = empties[i + 1];
                    break;
                }
            }
            String nexturl = "";
            URL uNext = new URL(url);
            result = GetHttpResult(url, null);

            // step 4
            // https://221.176.1.140:8090/roaming.php?Hotspot_operator=CMCC&Hotspot_location=beijing&Nas_id=9003.0591.591.00&Nas_ip=211.138.149.13&User_ip=183.250.17.62&Portal_ip=221.176.1.140:8080
            empties = result.split("\'");
            for (int i = 0; i < empties.length; i++) {
                if (empties[i].contains("src=")) {
                    // next 2 url
                    if (empties[i + 1].contains("roaming.php?")) {
                        nexturl = "https://" + uNext.getHost() + "/" + empties[i + 1];
                        // nexturl = url.replace("/input.php?",
                        // "/wlan/input.php?");
                        // nexturl =
                        // nexturl.replace("&wlanacssid=&fromlocation=index",
                        // "");
                        break;
                    }
                }
            }
            result = GetHttpResult(nexturl, null);
            Log.d(tag, "step4:"+result);
            // result = GetHttpResult(url, null);
            // empties = result.Split('\'');
            // for (int i = 0; i < empties.Length; i++)
            // {
            // if (empties[i].Contains("src="))
            // {
            // //next 2 url
            // url = empties[i + 1];
            // break;
            // }
            // }

            // step 5
            // https://221.176.1.140:8090/input.php?lang=&wlanacname=9003.0591.591.00&wlanacip=211.138.149.13&wlanuserip=183.250.19.208&wlanacssid=&fromlocation=do_login&st=login&lm=static&un=15896484824
            url = "https://" + uNext.getHost() + ":443/input.php?lang=&" + linfo + "&wlanacssid=&fromlocation=do_login&st=login&lm=static&un="
                    + uName;
            result = GetHttpResult(url, null);
            Log.d(tag, "step5:"+result);
            empties = result.split("\'");
            String loginvalidate = "";
            String loginhiddenvalidate = "";
            for (int i = 0; i < empties.length; i++) {
                if (empties[i] == "staticvalidateid" && loginvalidate == "") {
                    // next 2 url
                    loginvalidate = empties[i + 2].split("=")[empties[i + 2].split("=").length - 1];
                }

                if (empties[i] == "loginhiddenvalidate" && loginhiddenvalidate == "") {
                    // next 2 url
                    loginhiddenvalidate = empties[i + 4].trim();
                }
            }

            // step 6 https://221.176.1.140:8090/do_login.php
            url = "https://" + uNext.getHost() + ":8090/do_login.php";
            post = "staticusername=" + uName + "&staticpassword=" + uPassword + "&loginvalidate=" + loginvalidate + "&loginhiddenvalidate="
                    + loginhiddenvalidate + "&loginmode=static&" + linfo + "&wlanacssid=&issaveinfo=&staticsubmitname.x=0&staticsubmitname.y=1";
            result = GetHttpResult(url, post);
            Log.d(tag, "step6:"+result);
            if (result.contains(">alert(")) {
                empties = result.split("\"");
                for (int i = 0; i < empties.length; i++) {
                    if (empties[i].contains(">alert(")) {
                        url = empties[++i];
                        break;
                    }
                }
                // MessageBox.Show(url, "提示");
                return false;
            }
            if (result.contains("您好，您当前登录的用户已在线，是否继续操作")) {
                empties = result.split("\'");
                for (int i = 0; i < empties.length; i++) {
                    if (empties[i].contains("window.location")) {
                        // next 2 url
                        url = empties[i + 1];
                        break;
                    }
                }

                // step 7 relogin
                result = GetHttpResult(url, post);
                Log.d(tag, "step7:"+result);
            }
            empties = result.split("\'");
            for (int i = 0; i < empties.length; i++) {
                if (empties[i].contains("src=")) {
                    // next 2 url
                    m_LogoutData = empties[i + 1].split("?")[1];
                    break;
                }
            }
            m_Host = uNext.getHost();
        } catch (Exception ex) {
            Log.e("WebAuth", "认证出错：",ex);
            return false;
        }
        return true;
    }

    public boolean CMCCLogout() {
        String url = "http://" + m_Host + ":8080/do_logout.php";
        // String url = "https://221.176.1.140:443/do_logout.php";
        try {
            String result = GetHttpResult(url, m_LogoutData);
            if (result.contains("alert(\"下线成功\")")) {
                // MessageBox.Show("下线成功!", "提示");
                return true;
            } else {
                // MessageBox.Show("下线失败!", "提示");
                return false;
            }
        } catch (Exception e) {
            return false;
        }
    }

    public boolean CMCCEDULogin(String uName, String uPassword) {
        try {
            // step 1 打开百度
            String url = "http://www.baidu.com/";
            String result = GetHttpResult(url, null);
            String[] empties = result.split("\"");
            for (int i = 0; i < empties.length; i++) {
                if (empties[i].contains("URL=")) {
                    url = empties[i].substring(empties[i].indexOf("URL=") + 4);
                    break;
                }
            }

            // step 2
            result = GetHttpResult(url, null);
            empties = result.split("\"");
            for (int i = 0; i < empties.length; i++) {
                if (empties[i].contains("var url = ")) {
                    url = empties[i + 1] + "&redirect=www.baidu.com/";
                }
            }

            // step 3
            // HttpWebRequest request = GetHttpRequest(url, null, m_Cookies);
            // HttpWebResponse response =
            // (HttpWebResponse)request.GetResponse();
            // m_Cookies.Add(response.Cookies);
            // result = GetResponseContent(response);

            result = GetHttpResult(url, null);
            URL uNext = new URL(url);
            m_Host = uNext.getHost();
            empties = result.split("\"");
            for (int i = 0; i < empties.length; i++) {
                if (empties[i].contains("src=")) {
                    url = "http://" + m_Host + empties[i + 1];
                }
            }

            // step 4
            result = GetHttpResult(url, null);
            empties = result.split("\"");
            String post = "";
            String paramStr = "";
            for (int i = 0; i < empties.length; i++) {
                if (empties[i].contains("hidden")) {
                    if (post.contains(empties[i + 4]))
                        continue;
                    post += empties[i + 4] + "=" + URLEncoder.encode(empties[i + 6]) + "&";
                    if (empties[i + 4] == "paramStr")
                        paramStr = URLEncoder.encode(empties[i + 6]);
                }
            }

            // step 5 do login
            url = "http://" + m_Host + "/authServlet";
            if (post != "")
                post = post + "logon=%B5%C7+%C2%BC&UserName=" + uName + "&PassWord=" + uPassword;
            result = GetHttpResult(url, post);
            if (result.contains("您好，您当前登录的用户已在线，是否继续操作")) {
                empties = result.split("\'");
                for (int i = 0; i < empties.length; i++) {
                    if (empties[i].contains("window.location")) {
                        // next 2 url
                        url = empties[i + 1];
                        break;
                    }
                }

                // step 7 relogin
                result = GetHttpResult(url, post);
            }
            if (!result.contains("用户登录成功")) {
                // MessageBox.Show("登录失败!", "提示");
                return false;
            }

            m_LogoutData = "bOffline=true&paramStr=" + paramStr;
        } catch (Exception ex) {
            // MessageBox.Show("登录失败!" + ex.Message, "提示");
            return false;
        }
        // MessageBox.Show("登录成功!", "提示");
        return true;

    }

    public boolean CMCCEDULogout() {
        try {
            String url = "http://" + m_Host + "/logoutServlet";
            String result = GetHttpResult(url, m_LogoutData);
            if (!result.contains("下线成功")) {
                // MessageBox.Show("下线失败!" , "提示");
                return false;
            }
        } catch (Exception ex) {
            // MessageBox.Show("下线失败!" + ex.Message, "提示");
            return false;
        }
        // MessageBox.Show("下线成功!", "提示");
        return true;

    }

    public static String RemoveHTMLFlag(String input) {
        Matcher m = Pattern.compile("<script[^>]*?>.*?</script>", Pattern.CASE_INSENSITIVE).matcher(input);
        input = m.replaceAll("");
        m = Pattern.compile("<.+?>", Pattern.CASE_INSENSITIVE).matcher(input);
        input = m.replaceAll("");

        m = Pattern.compile("<(.[^>]*)>", Pattern.CASE_INSENSITIVE).matcher(input);
        input = m.replaceAll("");
        m = Pattern.compile("([\\r\\n])[\\s]+", Pattern.CASE_INSENSITIVE).matcher(input);
        input = m.replaceAll("");
        m = Pattern.compile("-->", Pattern.CASE_INSENSITIVE).matcher(input);
        input = m.replaceAll("");
        m = Pattern.compile("<!--.*", Pattern.CASE_INSENSITIVE).matcher(input);
        input = m.replaceAll("");
        m = Pattern.compile("&(quot|#34);", Pattern.CASE_INSENSITIVE).matcher(input);
        input = m.replaceAll("");
        m = Pattern.compile("&(amp|#38);", Pattern.CASE_INSENSITIVE).matcher(input);
        input = m.replaceAll("");
        m = Pattern.compile("&(lt|#60);", Pattern.CASE_INSENSITIVE).matcher(input);
        input = m.replaceAll("");
        m = Pattern.compile("&(gt|#62);", Pattern.CASE_INSENSITIVE).matcher(input);
        input = m.replaceAll("");
        m = Pattern.compile("&(nbsp|#160);", Pattern.CASE_INSENSITIVE).matcher(input);
        input = m.replaceAll("");
        m = Pattern.compile("&(iexcl|#161);", Pattern.CASE_INSENSITIVE).matcher(input);
        input = m.replaceAll("");
        m = Pattern.compile("&(cent|#162);", Pattern.CASE_INSENSITIVE).matcher(input);
        input = m.replaceAll("");
        m = Pattern.compile("&(pound|#163);", Pattern.CASE_INSENSITIVE).matcher(input);
        input = m.replaceAll("");
        m = Pattern.compile("&(copy|#169);", Pattern.CASE_INSENSITIVE).matcher(input);
        input = m.replaceAll("");
        m = Pattern.compile("&#(\\d+);", Pattern.CASE_INSENSITIVE).matcher(input);
        input = m.replaceAll("");
        input.replace("<", "");
        input.replace(">", "");
        input.replace("\r\n", "");
        return input;
    }
}
